package com.dizang.cloud.collapser.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import com.dizang.cloud.entity.User;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;

/**
 * 
 * @author kelvin.cai
 *
 */
public class UserBatchCollapser extends HystrixCollapser<List<User>, User, Long> {

    private Long id;

    public UserBatchCollapser(Long id) {
        super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("batch"))
                .andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter().withTimerDelayInMilliseconds(200)));
        this.id = id;
    }

    // 获取每一个请求的请求参数
    @Override
    public Long getRequestArgument() {
        return id;
    }

    // 创建命令请求合并
    @Override
    protected HystrixCommand<List<User>> createCommand(Collection<CollapsedRequest<User, Long>> requests) {
        List<Long> ids = new ArrayList<>(requests.size());
        ids.addAll(requests.stream().map(CollapsedRequest::getArgument).collect(Collectors.toList()));
        UserBatchCommand command = new UserBatchCommand("batch", ids);
        return command;
    }

    @Override
    protected void mapResponseToRequests(List<User> batchResponse, Collection<CollapsedRequest<User, Long>> requests) {
        System.out.println("分配批量请求结果");

        int count = 0;
        for (CollapsedRequest<User,Long> collapsedRequest : requests){
            User result = batchResponse.get(count++);
            collapsedRequest.setResponse(result);
        }

    }

}
